package org.common.utils.thread;
import java.util.Objects;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 默认的线程工厂实现
 * @author zhouzhibing
 * @date 2025/2/21
 */
public class DefaultThreadFactory implements ThreadFactory {

    /**
     * 默认的线程队列长度
     */
    public static final int DEFAULT_THREAD_QUEUE_LENGTH = 10000;

    /**
     * 前缀
     */
    private String prefix;

    /**
     * 索引
     */
    private AtomicInteger index = new AtomicInteger();


    public DefaultThreadFactory(String prefix) {
        this.prefix = prefix;
    }

    @Override
    public Thread newThread(Runnable r) {
        Objects.requireNonNull(r);
        Thread thread = new Thread(r);
        thread.setName(getName());
        return thread;
    }

    /**
     * 默认的线程队列
     * @return 返回一个新的线程队列
     */
    public BlockingQueue<Runnable> newBlockingQueue() {
        return new LinkedBlockingQueue<Runnable>(DefaultThreadFactory.DEFAULT_THREAD_QUEUE_LENGTH);
    }

    /**
     * 拼接线程名称
     * @return 线程名称
     */
    protected String getName() {
        return this.prefix + "-" + index.incrementAndGet();
    }
}
